package com.arpa.oms.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.http.server.HttpServerRequest;
import com.arpa.core.utils.collection.CollectionUtil;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.excel.EasyExcelUtil;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.oms.domain.dto.OmsGoodsDTO;
import com.arpa.oms.domain.dto.OmsGoodsRelationExcleDTO;
import com.arpa.oms.domain.vo.OmsGoodsRelationExcleVO;
import com.arpa.oms.domain.vo.OmsGoodsVO;
import com.arpa.oms.service.IOmsGoodsRelationService;
import com.arpa.wms.domain.consts.PropertyConst;
import com.arpa.wms.domain.dto.GoodsDTO;
import com.arpa.wms.domain.entity.Goods;
import com.arpa.wms.domain.enums.StatusEnum;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * OMS商品关系表 前端控制器
 * </p>
 *
 * @author spb
 * @since 2021-07-22
 */
@Api(tags = "组合商品管理")
@Log4j2(topic = "business")
@RestController
@RequestMapping(value = "/oms/goodsRelation", produces = "application/json;charset=UTF-8")
public class OmsGoodsRelationController {

    @Autowired
    private IOmsGoodsRelationService iOmsGoodsRelationService;

    @ApiOperation(value = "获取 组合商品 列表", notes = "获取 组合商品 列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = Goods.class))
    @NeedLogin
    @GetMapping
    public Result list(GoodsDTO goodsDTO, HttpServletRequest request) {
        try {
            Page returnPage = new Page(goodsDTO.getPageNum(), goodsDTO.getPageSize());
            Integer count = iOmsGoodsRelationService.listCount(goodsDTO);
            List<Goods> list = iOmsGoodsRelationService.listPage(goodsDTO);
            returnPage.setRecords(list);
            returnPage.setTotal(count);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation(value = "获取 组合商品 详情", notes = "获取 组合商品 详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = OmsGoodsDTO.class))
    @NeedLogin
    @GetMapping("/detail/{code}")
    public Result getInfoByCode(@PathVariable(value = "code", required = true) String code) {
        OmsGoodsVO omsGoodsVO = iOmsGoodsRelationService.getInfoByCode(code);
        return Result.ok().data(omsGoodsVO);
    }

    /**
     * 保存 组合商品
     *
     * @param entity
     * @param request
     * @return
     */
    @ApiOperation(value = "保存 组合商品 ", notes = "保存 组合商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功", response = OmsGoodsVO.class)
    })
    @NeedLogin
    @PostMapping
    public Result create(@RequestBody @Validated(OmsGoodsDTO.Save.class) OmsGoodsDTO entity, HttpServerRequest request) {
        try {
            if (entity != null && IterUtil.isNotEmpty(entity.getGoodsItems())) {
                iOmsGoodsRelationService.create(entity);
                return Result.ok("添加成功");
            } else {
                return Result.error("添加失败");
            }
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新 组合商品
     *
     * @param entity
     * @param request
     * @return
     */
    @ApiOperation(value = "更新 组合商品", notes = "更新 组合商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping
    public Result update(@RequestBody @Validated(OmsGoodsDTO.Save.class) OmsGoodsDTO entity, HttpServerRequest request) {
        if (null == entity || CollectionUtil.isEmpty(entity.getGoodsItems())) {
            return Result.error("数据不能为空");
        }
        iOmsGoodsRelationService.updateByCode(entity);
        return Result.ok("修改成功");
    }

    /**
     * 启用组合商品
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "启用 组合商品", notes = "启用 组合商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping("active")
    public Result active(@RequestParam List<String> codes, HttpServerRequest request) {
        if (CollectionUtil.isEmpty(codes)) {
            return Result.error("未获取到需要启用的记录");
        }
        Map<String, Integer> result = iOmsGoodsRelationService.batchUpdateStatus(codes, StatusEnum.ACTIVE.getValue());
        Integer success = MapUtil.getInt(result, PropertyConst.SUCCESS);
        int failNum = codes.size() - success;
        return Result.ok("启用成功" + success + "条；失败" + failNum + "条；");
    }

    /**
     * 停用组合商品
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "停用 组合商品", notes = "停用 组合商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping("unactive")
    public Result unactive(@RequestParam List<String> codes, HttpServerRequest request) {
        if (CollectionUtil.isEmpty(codes)) {
            return Result.error("未获取到需要停用的记录");
        }
        Map<String, Integer> result = iOmsGoodsRelationService.batchUpdateStatus(codes, StatusEnum.UNACTIVE.getValue());
        Integer success = MapUtil.getInt(result, PropertyConst.SUCCESS);
        int failNum = codes.size() - success;
        return Result.ok("停用成功" + success + "条；失败" + failNum + "条；");
    }

    /**
     * 删除 组合商品
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "停用 组合商品", notes = "停用 组合商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @DeleteMapping
    public Result delete(@RequestParam List<String> codes, HttpServerRequest request) {
        if (CollectionUtil.isEmpty(codes)) {
            return Result.error("未获取到需要删除的记录");
        }
        Map<String, Integer> result = iOmsGoodsRelationService.deleteByCodes(codes);
        Integer success = MapUtil.getInt(result, PropertyConst.SUCCESS);
        int failNum = codes.size() - success;
        return Result.ok("删除成功" + success + "条；失败" + failNum + "条；");
    }


    @ApiOperation(value = "组合商品 导入 预览", notes = "组合商品 导入 预览")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "filePath", value = "文件路径", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "isView", value = "是否已经预览", required = true, paramType = "query", dataType = "Integer")
    })
    @PostMapping("/goodsRelationExcelView")
    public Result goodsView(String filePath, Integer isView, HttpServletRequest request) {
        try {

            java.net.URL url = new java.net.URL(filePath);
            List<OmsGoodsRelationExcleDTO> list = EasyExcelUtil.read(url.openStream(), OmsGoodsRelationExcleDTO.class,2);
            if(CollUtil.isEmpty(list)) {
                throw new ServiceException("文件内容为空");
            }
            List<OmsGoodsRelationExcleVO> goodsExcelVOS = iOmsGoodsRelationService.goodsRelationExcelView(list);
            return new Result().data(goodsExcelVOS);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }
    @ApiOperation(value = "组合商品 导入 预览", notes = "组合商品 导入 预览")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "filePath", value = "文件路径", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "isView", value = "是否已经预览", required = true, paramType = "query", dataType = "Integer")
    })
    @PostMapping("/goodsRelationImport")
    public Result goodsRelationImport(@RequestParam("importCode") String importCode, HttpServletRequest request) {
        try {
            Result result = iOmsGoodsRelationService.importGoodsRelation(importCode);
            return result;
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }
}
